package org.btik.lightdev.dev;

import org.btik.light.meta.DevMo;
import org.btik.light.meta.event.cmd.DefaultCmd;
import org.btik.light.server.platform.common.api.dao.LightDao;
import org.btik.light.server.platform.common.api.service.DevAccessSever;
import org.btik.light.meta.Dev;
import org.btik.light.meta.base.Command;
import org.btik.light.meta.base.DevRpcServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import static org.btik.light.meta.LightDevAttrConstant.ACCESS_CHANNEL_TYPE;

@Service
public class DefaultDevRpcServer implements DevRpcServer {

    @Autowired
    private HashMap<String,DevAccessSever> devServerMap;

    @Autowired
    private LightDao lightDao;

    @Override
    public void sendCmd(Command command) {
        String sn = command.getTarget();
        DevMo mo = lightDao.getMO(sn);
        String type = mo.getExtendedAttributes().get(ACCESS_CHANNEL_TYPE);
        DevAccessSever devAccessSever = devServerMap.get(type);
        if(Objects.isNull(devAccessSever)){
            return;
        }
        Dev dev = devAccessSever.getDev(sn);
        dev.sendCmdOrMsg(command);
    }

    @Override
    public void sendCmd(Command command, String channelType) {
        DevAccessSever devAccessSever = devServerMap.get(channelType);
        if(devAccessSever == null){
            return;
        }
        Dev dev = devAccessSever.getDev(command.getTarget());
        dev.sendCmdOrMsg(command);
    }

    @Override
    public boolean isOnline(String sn) {
        DevMo mo = lightDao.getMO(sn);
        String type = mo.getExtendedAttributes().get(ACCESS_CHANNEL_TYPE);
        DevAccessSever devAccessSever = devServerMap.get(type);
        Dev dev = devAccessSever.getDev(sn);
        if (Objects.isNull(dev)) {
            return false;
        }
        return dev.isOnline();
    }

    @Override
    public void sendError(String str) {
        DefaultCmd defaultCmd = new DefaultCmd();
        defaultCmd.setOpcode(0);
        defaultCmd.setCmdId(0);
        defaultCmd.setParams(List.of(str));
        sendCmd(defaultCmd);
    }
}
